<template>
  <div class="p-2">
    <online-query-form ref="onlineQueryFormOuter" :id="ID" @search="queryWithCondition" @loaded="onQueryFormLoaded" />
    <BasicTable
      v-if="tableReloading"
      ref="onlineTable"
      :isTreeTable="true"
      :expandedRowKeys="expandedRowKeys"
      @expandedRowsChange="handleExpandedRowsChange"
      @expand="handleExpand"
      rowKey="autoRowKey"
      :canResize="true"
      :bordered="true"
      :showIndexColumn="false"
      :loading="loading"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      :rowSelection="rowSelection"
      :actionColumn="actionColumn"
      :showTableSetting="true"
      :clickToRowSelect="false"
      :scroll="tableScroll"
      @table-redo="reload"
      @change="handleChangeInTable"
      :class="enableScrollBar ? 'j-table-force-nowrap' : ''"
    >
      <template #tableTitle>
        <a-button v-if="buttonSwitch.add" preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
        <a-button v-if="buttonSwitch.import" preIcon="ant-design:import-outlined" type="primary" @click="onImportExcel">导入</a-button>
        <a-button v-if="buttonSwitch.export" preIcon="ant-design:export-outlined" type="primary" @click="onExportExcel">导出</a-button>
        <template v-if="cgTopButtonList && cgTopButtonList.length > 0" v-for="(item, index) in cgTopButtonList">
          <a-button
            v-if="item.optType == 'js'"
            :key="'cgbtn' + index"
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :preIcon="item.buttonIcon ? 'ant-design:' + item.buttonIcon : ''"
          >
            {{ item.buttonName }}
          </a-button>

          <a-button
            v-else-if="item.optType == 'action'"
            :key="'cgbtn' + index"
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :preIcon="item.buttonIcon ? 'ant-design:' + item.buttonIcon : ''"
          >
            {{ item.buttonName }}
          </a-button>
        </template>
        <a-button
          v-if="buttonSwitch.export"
          preIcon="ant-design:delete-outlined"
          type="primary"
          @click="handleBatchDelete"
          v-show="table.selectedRowKeys.length > 0"
          >批量删除</a-button
        >
        <online-super-query v-if="buttonSwitch.super_query" ref="superQueryButtonRef" online :status="superQueryStatus" @search="handleSuperQuery" />
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px, font-style: italic">无图片</span>
        <img v-else :src="getImgView(text)" alt="图片不存在" class="online-cell-image" @click="viewOnlineCellImage(text)" />
      </template>
      <template #htmlSlot="{ text }">
        <div>{{ text }}</div>
      </template>
      <template #pcaSlot="{ text }">
        <div :title="getPcaText(text)">{{ getPcaText(text) }}</div>
      </template>
      <template #dateSlot="{ text }">
        <span>{{ getFormatDate(text) }}</span>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getActions(record)" :dropDownActions="getDropDownActions(record)" />
      </template>
    </BasicTable>
    <OnlineAutoModal :id="ID" @register="registerModal" @success="reload" :formConfig="handleFormConfig" />
    <online-detail-modal :id="ID" @register="registerDetailModal" />
    <JImportModal :id="ID" @register="registerImportModal" :url="importUrl()" @ok="reload" online />
    <a-modal v-bind="hrefComponent.model" v-on="hrefComponent.on">
      <resolveDynamicComponent :is="hrefComponent.is" v-bind="hrefComponent.params" />
    </a-modal>
    <online-custom-modal :id="ID" @register="registerCustomModal" @success="reload" />
    <online-detail-modal :id="hrefMainTableId" @register="registerOnlineHrefModal" :defaultFullscreen="false" />
    <online-pop-modal ref="onlinePopModalRef" :id="popTableId" @register="registerPopModal" @success="reload" request toptip />
  </div>
</template>
<script lang="ts">
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import OnlineAutoModal from '../default/OnlineAutoModal.vue';
  import OnlineDetailModal from '../default/OnlineDetailModal.vue';
  import OnlineCustomModal from '../default/OnlineCustomModal.vue';
  import { ref, watch, defineComponent, resolveDynamicComponent } from 'vue';
  import JImportModal from '/@/components/Form/src/jeecg/components/JImportModal.vue';
  import { useOnlineTableContext, useListButton } from '../../use/useListButton';
  import { useEnhance, useTableColumns, getRefPromise } from '../../use/useAutoForm';
  import { defHttp } from '/@/utils/http/axios';
  import OnlineQueryForm from '../comp/OnlineQueryForm.vue';
  import OnlineSuperQuery from '../comp/superquery/SuperQuery.vue';

  export default defineComponent({
    name: 'DefaultOnlineList',
    components: {
      BasicTable,
      TableAction,
      OnlineAutoModal,
      JImportModal,
      OnlineQueryForm,
      OnlineSuperQuery,
      OnlineCustomModal,
      OnlineDetailModal,
      resolveDynamicComponent,
    },
    setup() {
      const { createMessage: $message } = useMessage();
      const onlineTreeTableRef = ref();
      const {
        ID,
        onlineTableContext,
        onlineQueryFormOuter,
        loading,
        reload,
        dataSource,
        pagination,
        handleSpecialConfig,
        getColumnList,
        handleChangeInTable,
        loadData,
        superQueryButtonRef,
        superQueryStatus,
        handleSuperQuery,
        registerCustomModal,
        getTreeDataByResult,
        expandedRowKeys,
        handleExpandedRowsChange,
        tableReloading,
        onlineExtConfigJson,
        handleFormConfig,
      } = useOnlineTableContext();
      if (!ID.value) {
        $message.warning('地址错误, 配置ID不存在!');
        return;
      }
      onlineTableContext.isTree(true);
      let { initCgEnhanceJs } = useEnhance(onlineTableContext);
      const {
        buttonSwitch,
        cgLinkButtonList,
        cgTopButtonList,
        importUrl,
        registerModal,
        handleAdd,
        handleEdit,
        handleBatchDelete,
        registerImportModal,
        onImportExcel,
        onExportExcel,
        cgButtonJsHandler,
        cgButtonActionHandler,
        cgButtonLinkHandler,
        handleSubmitFlow,
        getDropDownActions,
        getActions,
        initButtonList,
        initButtonSwitch,
        registerDetailModal,
      } = useListButton(onlineTableContext, onlineExtConfigJson);
      const {
        columns,
        actionColumn,
        selectedKeys,
        rowSelection,
        enableScrollBar,
        tableScroll,
        downloadRowFile,
        getImgView,
        getPcaText,
        getFormatDate,
        handleColumnResult,
        hrefComponent,
        viewOnlineCellImage,
      } = useTableColumns(onlineTableContext, onlineExtConfigJson);
      watch(
        ID,
        () => {
          initAutoList();
        },
        { immediate: true }
      );
      async function initAutoList() {
        loading.value = true;
        let columnResult = await getColumnList();
        handleTableConfig(columnResult);
        await loadData();
        loading.value = false;
        onlineTableContext.execButtonEnhance('setup');
      }
      function handleTableConfig(result) {
        let EnhanceJS = initCgEnhanceJs(result.enhanceJs);
        onlineTableContext['EnhanceJS'] = EnhanceJS;
        initButtonList(result.cgButtonList);
        initButtonSwitch(result.hideColumns);
        handleColumnResult(result);
        handleSpecialConfig(result);
        onlineTableContext['hasChildrenField'] = result.hasChildrenField;
        onlineTableContext['pidField'] = result.pidField;
      }
      function queryWithCondition(data, status) {
        onlineTableContext['queryParam'] = data;
        if (status === true) {
          reload();
        } else {
          searchReset();
        }
      }
      async function onQueryFormLoaded(json) {
        await getRefPromise(superQueryButtonRef);
        superQueryButtonRef.value.init(json);
      }
      function handleExpand(expanded, record) {
        let expandedRowKeysValue = expandedRowKeys.value;
        if (expanded) {
          addExpandedRowKey(record.id);
          if (record.children.length > 0 && record.children[0].isLoading === true) {
            let hasChildrenField = onlineTableContext.hasChildrenField;
            const { sortField, sortType } = onlineTableContext;
            let params = Object.assign({}, { column: sortField, order: sortType });
            params[onlineTableContext['pidField']] = record.id;
            params[hasChildrenField] = record[hasChildrenField];
            let url = `${onlineTableContext.onlineUrl.getTreeData}${onlineTableContext.ID}`;
            defHttp
              .get({ url, params }, { isTransformResponse: false })
              .then((res) => {
                console.log('handleExpand', res.data);
                if (res.success) {
                  if (Number(res.data.records) > 0) {
                    record.children = getTreeDataByResult(res.data.records);
                  } else {
                    record.children = '';
                    record.hasChildrenField = '0';
                  }
                } else {
                  $message.warning(res.msg);
                }
              })
              .catch(() => {
                $message.warning('加载子节点失败!');
              });
          }
        } else {
          let keyIndex = expandedRowKeysValue.indexOf(record.id);
          if (keyIndex >= 0) {
            expandedRowKeys.value = expandedRowKeysValue.splice(keyIndex, 1);
          }
        }
      }
      function addExpandedRowKey(key) {
        let arr = expandedRowKeys.value;
        if (arr && arr.indexOf(key) < 0) {
          arr.push(key);
        }
        expandedRowKeys.value = arr;
      }
      async function searchReset() {
        if (onlineTableContext.isTree() === true) {
          expandedRowKeys.value = [];
          onlineTreeTableRef.value.collapseAll();
        }
        reload();
      }
      function handlerFormSuccess(formData) {
        console.log('expandedRowKeys.value', expandedRowKeys.value);
        if (loadParent.value === true) {
          let pid = formData[onlineTableContext.pidField];
          if (pid) {
            let arr = expandedRowKeys.value;
            if (arr.indexOf(pid) < 0) {
              arr.push(pid);
            }
            expandedRowKeys.value = arr;
          }
        }
        reload();
      }
      const addChildButton = (record) => {
        return {
          label: '添加下级',
          onClick: handleAddChild.bind(null, record),
        };
      };
      const loadParent = ref(false);
      function handleAddChild(record) {
        loadParent.value = true;
        let param = {
          [onlineTableContext.pidField]: record['id'],
        };
        handleAdd(param);
      }
      function getTreeDropDownActions(record) {
        let arr = getDropDownActions(record);
        arr.unshift(addChildButton(record));
        return arr;
      }
      const that = {
        ID,
        onlineQueryFormOuter,
        queryWithCondition,
        onQueryFormLoaded,
        reload,
        superQueryButtonRef,
        superQueryStatus,
        handleSuperQuery,
        loading,
        columns,
        actionColumn,
        dataSource,
        pagination,
        rowSelection,
        selectedKeys,
        tableScroll,
        enableScrollBar,
        handleChangeInTable,
        buttonSwitch,
        handleAdd,
        handleEdit,
        onImportExcel,
        onExportExcel,
        cgTopButtonList,
        cgLinkButtonList,
        cgButtonJsHandler,
        cgButtonActionHandler,
        cgButtonLinkHandler,
        handleBatchDelete,
        downloadRowFile,
        getImgView,
        getPcaText,
        getFormatDate,
        getActions,
        getTreeDropDownActions,
        registerModal,
        registerCustomModal,
        registerImportModal,
        importUrl,
        handleFormConfig,
        tableReloading,
        handleSubmitFlow,
        hrefComponent,
        viewOnlineCellImage,
        onlineTreeTableRef,
        handlerFormSuccess,
        searchReset,
        handleExpand,
        expandedRowKeys,
        handleExpandedRowsChange,
        registerDetailModal,
      };
      return that;
    },
  });
</script>

<style scoped>
  .online-cell-image {
    height: 25px !important;
    margin: 0 auto;
    max-width: 80px;
    font-size: 12px;
    font-style: italic;
  }

  .j-table-force-nowrap td,
  .j-table-force-nowrap th {
    white-space: nowrap;
  }

  .j-table-force-nowrap .ant-table-selection-column {
    padding: 12px 22px !important;
  }

  .j-table-force-nowrap.ant-table-wrapper .ant-table-content {
    overflow-x: auto;
  }
</style>
